package com.br.aiops.listeners.ladder;

import com.br.aiops.alert.AlertSender;
import com.br.aiops.config.ApplicationContextUtil;
import com.br.aiops.counter.AlertLogCounter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

public abstract class AbstractLadderJudge {

    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractLadderJudge.class);

    protected AlertLogCounter counter;

    protected Map<String, LadderCycleStatus> cycleStatusCache = LadderCycleStatusCache.getLadderCycleStatus();

    public AbstractLadderJudge(AlertLogCounter counter) {
        this.counter = counter;
    }

    /**
     * 执行阶梯任务；如果需要告警，则会升级阈值；
     */
    public abstract void judgeLadder();

    public LadderCycleStatus initCycleIfAbsent() {
        //没有周期状态则新建；同时初始化；否则直接返回周期状态
        return cycleStatusCache.computeIfAbsent(counter.counterKey(), k -> {
            LadderCycleStatus cycleStatus = new LadderCycleStatus(counter);
            cycleStatus.initCycle();
            return cycleStatus;
        });
    }

    public LadderCycleStatus countCycle(LadderCycleStatus counterStatus) {
        counterStatus.count(counter.getAlertLog().getLogTime());
        return counterStatus;
    }

    protected void sendAlert() {
        ApplicationContextUtil.getBean(AlertSender.class).sendAlertMessage(counter);
    }
}
